extends Node2D

@export var mapLayer:TileMapLayer
@export var hightLightLayer:TileMapLayer
@export var selectLayer:TileMapLayer

@onready var battle_ui: BattleUI = $BattleUI
@onready var player_handler: PlayerHandler = $PlayerHandler

var curMouseCell:Vector2i


func _input(event: InputEvent) -> void:
	# 根据鼠标位置，获取 map 的 cell 坐标
	var newMouseCell: Vector2i = selectLayer.local_to_map(get_global_mouse_position())
	if curMouseCell == newMouseCell:
		return
	selectLayer.erase_cell(curMouseCell)
	curMouseCell = newMouseCell
	if mapLayer.get_cell_source_id(curMouseCell) == -1:
		return
	selectLayer.set_cell(curMouseCell, 0, Vector2i(0,0))
	


func _ready() -> void:
	var player_units:Array = get_tree().get_nodes_in_group("player")
	var temp_unit:Player
	for unit:Player in player_units:	 
		var new_stats: CharacterStats = unit.stats.create_instance()
		unit.set_character_stats(new_stats)
		temp_unit = unit
		unit.position = TileMapUtil.convert_layer_coordinate_2_globle_p(unit.cur_cell, mapLayer)
		

	Events.player_turn_ended.connect(player_handler.end_turn)
	Events.player_hand_discarded.connect(player_handler.start_turn)

	start_battle(temp_unit.stats)

func start_battle(stats: CharacterStats) -> void:
	player_handler.start_battle(stats)
